package org.chen;

import org.chen.pool.JedisConnect;
import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeoJedisTest {
  public static void main(String[] args) {
    JedisConnect connect = new JedisConnect();
    connect.execute(jedis -> {
      jedis.flushDB();

      //添加城市地理位置
      Map<String, GeoCoordinate> geoCoordinate = new HashMap<>();
      geoCoordinate.put("shanghai", new GeoCoordinate(121.48, 31.22));
      geoCoordinate.put("beijing", new GeoCoordinate(116.46, 39.92));
      geoCoordinate.put("shenzhen", new GeoCoordinate(114.07, 22.62));
      geoCoordinate.put("chengdu", new GeoCoordinate(104.06, 30.67));
      geoCoordinate.put("chongqing", new GeoCoordinate(106.54, 29.59));
      jedis.geoadd("city", geoCoordinate);

      //获取key中指定城市的经度和纬度
      System.out.println(jedis.geopos("city", "shanghai"));//[(121.48000091314316,31.21999956478424)]

      //返回两个城市之间的直线距离
      System.out.println(jedis.geodist("city", "shanghai", "shenzhen",
        GeoUnit.KM));//1205.4337

      //返回以给定经纬度为中心，半径为radius以内的城市
      List<GeoRadiusResponse> cities = jedis.georadius("city", 116, 28, 1000,
        GeoUnit.KM);
      for (GeoRadiusResponse city : cities) {
        System.out.println(city.getMemberByString());
        //shenzhen
        //shanghai
        //chongqing
      }

      //以给定的城市为中心，返回半径范围内的城市
      List<GeoRadiusResponse> list = jedis.georadiusByMember("city", "chengdu", 1000,
        GeoUnit.KM);
      for (GeoRadiusResponse city : list) {
        System.out.println(city.getMemberByString());
        //chengdu
        //chongqing
      }

      //将城市的经纬度坐标以Geohash 表示
      System.out.println(jedis.geohash("city", "shanghai"));//[wtw3s77j9j0]

      //geo存储的元素可以用zset命令操作，如查看city的所以元素，删除city的某个元素
      //其原因是geo的底层实现原理就是zset
    });
  }
}
